package services

import (
	"demo/models"
	"demo/pkg/database"
	"demo/pkg/notice"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func sendPaymentNotificationToUser(c *gin.Context, payment *models.Payments) {
	user, err := database.GetUserinfoByUserId(payment.UserId)
	if err != nil || user == nil {
		logrus.Errorln("failed to get user info: ", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get user info"})
		return
	}

	// 生成支付成功通知的标题和内容
	title := "【原始人电力公司】支付成功通知"
	content := fmt.Sprintf(
		"尊敬的用户，\n\n"+
			"您好！感谢您使用原始人电力公司的服务。我们已收到您本期电费账单的支付。以下是支付详情：\n\n"+
			"支付编号: %d\n"+
			"账单编号: %d\n"+
			"支付日期: %s\n"+
			"支付金额: %.2f 元\n"+
			"支付方式: %s\n\n"+
			"感谢您的及时支付。如有任何疑问，请联系原始人电力公司客服。\n\n"+
			"谢谢！\n原始人电力公司",
		payment.Id,
		payment.BillId,
		payment.PaymentDate.Format("2006-01-02 15:04:05"),
		payment.Amount,
		payment.PaymentMethod,
	)

	noticeMsg := &models.NoticeMsg{
		Title:    title,
		Content:  content,
		UserNums: []string{user.Email},
		Type:     "email",
	}

	err = notice.SendNoticeToUser(noticeMsg)
	if err != nil {
		logrus.Errorln("failed to send notice to user: ", err)
		return
	}

	// 插入通知记录到 notifications 表
	notification := models.Notifications{
		UserId:    user.Id,
		Message:   content,
		IsRead:    0,
		Timestamp: time.Now(),
	}
	err = database.InsertOneNotice(&notification)
	if err != nil {
		logrus.Errorln("failed to insert notice: ", err)
		return
	}
}

func OkPay(c *gin.Context) {
	paymentIDStr := c.Param("id")                // 获取路径参数中的 payment ID
	paymentID, err := strconv.Atoi(paymentIDStr) // 将 payment ID 转换为整数
	if err != nil {
		logrus.Error("invalid payment ID: ", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payment ID"})
		return
	}

	payment, err := database.GetPaymentById(paymentID)
	if err != nil {
		logrus.Error("failed to get payment info: ", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get payment info"})
		return
	}

	// 发送支付成功通知
	sendPaymentNotificationToUser(c, payment)

	c.JSON(http.StatusOK, gin.H{"message": "payment processed successfully"})
}
